
import UserInfo from 'central/UserInfo';
import qs from 'query-string';
import history from 'router/history'
import { server } from 'server';

const APP_ID = 'wx42a22605f2a048d5';

export const wx = window['wx'] as any;

/** 微信登陆 */
export const authorize = async () => {

    /** 是否已经登陆 */
    if (UserInfo.instance.state.token) {
        return;
    };

    const code = qs.parse(window.location.search).code;

    if (code) {
        const state = qs.parse(window.location.search).state as string;
        history.replace(`/wxSignIn?code=${code}${state && `&state=${encodeURIComponent(state)}`}`)
    } else {
        const redirect_uri = encodeURIComponent(window.location.href.split('#')[0])
        const state = encodeURIComponent(window.location.href.split('#')[1])
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect `
        // window.location.href = url;
        window.location.replace(url);
    }
}

/** JS 授权 */
export const jsAuthorize = async () => {
    const ajax = await server.get(`/wx/jsapi/${APP_ID}/getJsapiTicket`).end()
    wx.config({
        debug: true,
        appId: APP_ID, 
        timestamp:ajax.res.body.timestamp, 
        nonceStr: ajax.res.body.nonceStr, 
        signature: ajax.res.body.signature,
        jsApiList: ['chooseWXPay', 'scanQRCode'] // 必填，需要使用的JS接口列表
    }); 

    wx.ready(function () {
        console.log('jds 鉴权成功');
    });
}